package kin.serviceIMP.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import kin.bean.security.Module;
import kin.manager.security.ModuleManager;
import kin.service.security.ModuleServiceManager;
import kin.serviceIMP.system.BaseServiceManagerIMP;
import kin.test.Tree;
@Service
public class ModuleServiceManagerIMP extends BaseServiceManagerIMP<Module> implements ModuleServiceManager{
	


	


	public List find() {
		// TODO Auto-generated method stub
		return null;
	}

	public List<Module> findParentModuleByRole(Set<String> s) throws Exception {
		LinkedHashMap<String, Collection> in=new  LinkedHashMap<String, Collection>();  
		in.put("module_url", s);
		
		List<Module> l= this.findList(null, in, null,null);
		
		List<Module> mp=new ArrayList<Module>();
		
		for(Module m:l){
			if(m.isRenderToNAV()){
				m.setChildren(new ArrayList());
			mp.add(m);
			}
		}
		
		
		List<Module> ms=new ArrayList<Module>();
		/*for(Module m:l){
			//
			//m.getChildren().clear();
			m.setChildren(new ArrayList());
			
	//m.getChildren().removeAll(c);
			if(m.isLeaf()==false){
				mp.add(m);
			}else{
				ms.add(m);
			}
		
		}*/
		
		/*for(Module m:mp){
			System.out.println("id:"+m.getModule_id());
		
		
		
		for(Module mm:mp){
			
			for(Module mms:ms){
				
				if((mms.getParent().getModule_id()==mm.getModule_id())&&mms.isRenderToNAV()){
					mm.getChildren().add(mms);
				}
				
			}
			/*if(mm.getChildren().size()==0){
				mp.remove(mm);
			
			
		}}*/
		
		Tree t=new Tree();
		t.buildTree(mp, null);
		//System.out.println("resourceMap:"+resourceMap);
		return t.getRoots();
		//return this.moduleManager.getSessionFactory().getCurrentSession().createSQLQuery("SELECT * FROM t_module AS p WHERE p.module_parent_module_id IS NULL AND p.module_url IN (:as) AND p.renderToNAV = 1 AND EXISTS (SELECT * FROM t_module AS c  WHERE c.module_parent_module_id = p.module_id  AND c.renderToNAV = 1)").setParameterList("as", s).list();
		//return mp;
		
	}

	

	public List<Module> findAllNAV() throws Exception {
		
		return this.getSessionFactory().getCurrentSession().createQuery("FROM Module AS p WHERE p.module_parent_module_id IS NULL AND p.renderToNAV=1 AND EXISTS ( FROM Module AS c WHERE c.module_parent_module_id=p.module_id AND c.renderToNAV=1)").list();
	}

	@Override
	public void deleteByUrl(String url) {
		this.getSessionFactory().getCurrentSession().createQuery("FROM Module AS p WHERE p.module_parent_module_id IS NULL AND p.renderToNAV=1 AND EXISTS ( FROM Module AS c WHERE c.module_parent_module_id=p.module_id AND c.renderToNAV=1)").list();
		
	}

}
